//
//  WCPreferencesWindowController.m
//  WabbitCode
//
//  Created by William Towe on 1/7/09.
//  Copyright 2009 Revolution Software. All rights reserved.
//

#import "WCPreferencesWindowController.h"
#import "WCMacros.h"
#import "NSArray+WCExtensions.h"
#import "WCAppController.h"
#import "WCTextView.h"
#import "EncodingManager.h"
#import "WCNewTextFileProcessor.h"
#import "WCSyntaxHighlighter.h"
#import "WCIconAndTextFieldCell.h"


@implementation WCPreferencesWindowController
#pragma mark -
#pragma mark *** Subclass Overrides ***
+ (NSString *)nibName; {
	return @"WCPreferencesWindow";
}

- (void)windowWillLoad {
	[super windowWillLoad];
	
}

- (void)windowDidLoad {
	[super windowDidLoad];
	
	NSMutableArray *items = [NSMutableArray array];
	for (NSTabViewItem *item in [_tabView tabViewItems]) {
		[items addObject:[NSDictionary dictionaryWithObjectsAndKeys:[item label], @"name", [NSImage imageNamed:[item identifier]], @"icon", nil]];
	}
	[self setAdvancedTabViewItems:items];
	
	[_encodingButton setEncoding:NSUserDefaultsUnsignedIntegerForKey(kWCPrefsEditorDefaultFileEncodingKey) defaultEntry:YES];
}

- (void)setupToolbar; {
	[self addView:_general label:NSLocalizedString(@"General",@"General") image:[NSImage imageNamed:NSImageNamePreferencesGeneral]];
	[self addView:_colors label:NSLocalizedString(@"Colors",@"Colors") image:[NSImage imageNamed:NSImageNameColorPanel]];
	[self addView:_building label:NSLocalizedString(@"Building",@"Building")];
	//[self addView:_console label:NSLocalizedString(@"Console",@"Console")];
	[self addView:_debugger label:NSLocalizedString(@"Debugging",@"Debugging")];
	[self addView:_editor label:NSLocalizedString(@"Editor",@"Editor")];
	[self addView:_files label:NSLocalizedString(@"Files",@"Files")];
	[self addView:_tabs label:NSLocalizedString(@"Tabs",@"Tabs")];
	[self addView:_advanced label:NSLocalizedString(@"Advanced",@"Advanced") image:[NSImage imageNamed:NSImageNameAdvanced]];
	//[self addView:_updates label:NSLocalizedString(@"Software Update",@"Software Update")];
}

- (IBAction)changeFont:(id)sender; {
	NSFontManager *fontManager = [NSFontManager sharedFontManager];
	NSFont *panelFont = [fontManager convertFont:[fontManager selectedFont]];
	NSSetUserDefaultsObjectForKey(NSKeyedArchivedObject(panelFont), kWCPrefsEditorFontKey);
}

#pragma mark NSPathControl Delegate
- (NSDragOperation)pathControl:(NSPathControl *)pathControl validateDrop:(id <NSDraggingInfo>)info {
	if (![pathControl isEnabled])
		return NSDragOperationNone;
	
	if (![[[info draggingPasteboard] types] containsObject:NSFilenamesPboardType])
		return NSDragOperationNone;
	
	NSArray *fileNames = [[info draggingPasteboard] propertyListForType:NSFilenamesPboardType];
	
	if ([fileNames count] != 1)
		return NSDragOperationNone;
	
	BOOL isDirectory = NO;
	if (![[NSFileManager defaultManager] fileExistsAtPath:[fileNames firstObject] isDirectory:&isDirectory] || !isDirectory)
		return NSDragOperationNone;
	return NSDragOperationCopy;
}

- (BOOL)pathControl:(NSPathControl *)pathControl acceptDrop:(id <NSDraggingInfo>)info {
	NSSetUserDefaultsObjectForKey([[[info draggingPasteboard] propertyListForType:NSFilenamesPboardType] firstObject], kWCPrefsBuildingProductsCustomDirectoryKey);
	return YES;
}
#pragma mark NSSplitView Delegate
- (CGFloat)splitView:(NSSplitView *)splitView constrainMinCoordinate:(CGFloat)proposedMin ofSubviewAt:(NSInteger)offset {
	if ([splitView isVertical])
		return proposedMin + 50.0;
	return proposedMin;
}

- (CGFloat)splitView:(NSSplitView *)splitView constrainMaxCoordinate:(CGFloat)proposedMax ofSubviewAt:(NSInteger)offset {
	if ([splitView isVertical])
		return proposedMax - 150.0;
	return proposedMax;
}

- (NSRect)splitView:(NSSplitView *)splitView additionalEffectiveRectOfDividerAtIndex:(NSInteger)dividerIndex {
	if ([splitView isVertical]) {
		return NSMakeRect(NSMaxX([_gradientBarView bounds]) - [_leftSplitterHandleImageView frame].size.width, [splitView frame].size.height - [_gradientBarView frame].origin.y - [_gradientBarView bounds].size.height, [_leftSplitterHandleImageView frame].size.width, [_gradientBarView bounds].size.height);
	}
	return NSZeroRect;
}
#pragma mark NSTableView Delegate
- (void)tableView:(NSTableView *)tableView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
	NSDictionary *dict = [[[tableView dataSource] arrangedObjects] objectAtIndex:row];
	
	[cell setIcon:[dict objectForKey:@"icon"]];
	[cell setIconSize:NSMakeSize(24.0, 24.0)];
}

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row {
	return 30.0;
}

- (void)tableViewSelectionDidChange:(NSNotification *)note {	
	[_tabView selectTabViewItemAtIndex:[[[[note object] dataSource] selectionIndexes] firstIndex]];
}
#pragma mark -
#pragma mark *** Public Methods ***
#pragma mark Accessors
@synthesize advancedTabViewItems=_advancedTabViewItems;
#pragma mark IBActions
- (IBAction)chooseFontAction:(id)sender; {
	[[sender window] makeFirstResponder:nil];
	
	NSFontManager *fontManager = [NSFontManager sharedFontManager];
	[fontManager setDelegate:self];
	[fontManager setSelectedFont:[NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:kWCPrefsEditorFontKey]] isMultiple:NO];
	[fontManager orderFrontFontPanel:nil];
}

- (IBAction)chooseBuildProductsCustomDirectoryAction:(id)sender; {
	NSOpenPanel *panel = [NSOpenPanel openPanel];
	
	[panel setCanChooseFiles:NO];
	[panel setCanChooseDirectories:YES];
	
	[panel beginSheetForDirectory:NSHomeDirectory() file:nil modalForWindow:[self window] modalDelegate:self didEndSelector:@selector(_chooseBuildProductsCustomDirectoryOpenPanelDidEnd:code:info:) contextInfo:NULL];
}

- (IBAction)changeDefaultFileEncodingAction:(id)sender; {
	NSSetUserDefaultsUnsignedIntegerForKey([sender selectedTag], kWCPrefsEditorDefaultFileEncodingKey);
}
#pragma mark -
#pragma mark *** Private Methods ***
#pragma mark Callbacks
- (void)_chooseBuildProductsCustomDirectoryOpenPanelDidEnd:(NSOpenPanel *)panel code:(NSInteger)code info:(void *)info {
	if (code != NSOKButton)
		return;
	
	NSSetUserDefaultsObjectForKey([panel directory], kWCPrefsBuildingProductsCustomDirectoryKey);
}
@end
